extends Node2D

@onready var debris = preload("res://debris.tscn")
@onready var alien = preload("res://alien.tscn")
@onready var char = $Character
var score = 0

func _input(event):
	if event.is_action_pressed("esc"):
		get_tree().reload_current_scene()

func _on_timer_timeout() -> void:
	var y = debris.instantiate()
	var x = randi_range(1, 4)
	if x == 1:
		y.global_position = Vector2(char.global_position.x+2000, char.global_position.y+randi_range(-2000, 2000))
	elif x == 2:
		y.global_position = Vector2(char.global_position.x-2000, char.global_position.y+randi_range(-2000, 2000))
	elif x == 3:
		y.global_position = Vector2(char.global_position.x+randi_range(-2000, 2000), char.global_position.y+2000)
	elif x == 4:
		y.global_position = Vector2(char.global_position.x+randi_range(-2000, 2000), char.global_position.y-2000)
	add_child(y)
	y.name += "debris"

func setscore(sc):
	score += sc
	$CanvasLayer/UI/Label.text = "Score: " + str(score)
	if sc > 0:
		$CanvasLayer/UI/Label4.text = "+" + str(sc)
		$CanvasLayer/UI/Label4.modulate.a = 1
		var tween = get_tree().create_tween()
		tween.tween_property($CanvasLayer/UI/Label4, "modulate:a", 0, 1)
	
func die():
	$CanvasLayer/UI.die()
	$Timer3.stop()

		
func startgame():
	if not $AudioStreamPlayer.is_playing():
		$AudioStreamPlayer.play()
	score = 0
	setscore(0)
	for i in get_children():
		if "debris" in i.name or "bubble" in i.name or "alien" in i.name:
			i.queue_free()
	$ParallaxBackground/ParallaxLayer2.position = Vector2(randi(), randi())
	$ParallaxBackground/ParallaxLayer4.position = Vector2(randi(), randi())
	$Character.bubblegrowing = false
	$Character.netswinging = false
	$Character.bubble = null
	$Character.pointerdir = null
	$Character.dead = false
	$Character.bubbletype = 0
	$Tutorial.visible = true
	$Character.velocity = Vector2(0, 0)
	$Character/CharacterSprite.animation = "0normal"
	$Timer.start()
	$Timer2.start()
	$Timer3.start()


func _on_timer_2_timeout() -> void:
	var y = alien.instantiate()
	var x = randi_range(1, 4)
	if x == 1:
		y.global_position = Vector2(char.global_position.x+2000, char.global_position.y+randi_range(-2000, 2000))
	elif x == 2:
		y.global_position = Vector2(char.global_position.x-2000, char.global_position.y+randi_range(-2000, 2000))
	elif x == 3:
		y.global_position = Vector2(char.global_position.x+randi_range(-2000, 2000), char.global_position.y+2000)
	elif x == 4:
		y.global_position = Vector2(char.global_position.x+randi_range(-2000, 2000), char.global_position.y-2000)
	add_child(y)
	y.name += "alien"


func _on_timer_3_timeout() -> void:
	setscore(25)
